package cn.starrysky108.simpleerp.core.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * redis配置文件
 * 开启缓存支持，注入RedisTemplate
 *
 * @author Carl Lee
 */
@Configuration
@EnableCaching
public class RedisConfig {
    /**
     * redis配置，默认key为String类型
     *
     * @param mapper 使用spring boot默认配置好的的ObjectMapper,否则需要对java8的时间类型重新社会序列化器
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory, ObjectMapper mapper) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        StringRedisSerializer keySerializer = new StringRedisSerializer();
        //注入jackson2配置的objectMapper.否则在序列化java8 时间Api会报错
        GenericJackson2JsonRedisSerializer valueSerializer = new GenericJackson2JsonRedisSerializer(mapper);
        template.setKeySerializer(keySerializer);
        //强制默认hashKey类型为String
        template.setHashKeySerializer(keySerializer);
        template.setValueSerializer(valueSerializer);
        template.setHashValueSerializer(valueSerializer);
        template.setConnectionFactory(redisConnectionFactory);
        //开启事务支持
        template.setEnableTransactionSupport(true);
        return template;
    }
}
